﻿using System;
using System.Linq;
using System.Linq.Expressions;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.ObjectModel;
using System.Data;
using System.Collections.Generic;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
	public class NewsRepository : BaseRepository<News>, INewsRepository
	{
		public NewsRepository(IContextContainer container) : base(container)
		{
		}

		public void InsertOnSubmit(News entity)
		{
			CurrentObjectSet.AddObject(entity);
		}

		public void Update(News entity)
		{
			CurrentObjectSet.Attach(entity);
			Context.ChangeObjectState(entity, EntityState.Modified);
		}

		public void DeleteOnSubmit(News entity)
		{
			CurrentObjectSet.DeleteObject(entity);
		}

		public void SubmitChanges()
		{
			SaveChanges();
		}

		public List<NewsDTO> GetLastNewsDTO(int number)
		{
			return CurrentObjectSet.AsQueryable().OrderByDescending(n => n.PublicationDate).Take(number).SelectDTO<News, NewsDTO>().ToList();
		}

		public IQueryable<News> GetAll()
		{
			return CurrentObjectSet;
		}

		public IQueryable<News> Where(Expression<Func<News, bool>> predicate)
		{
			return CurrentObjectSet.Where(predicate);
		}

		public long Count(Expression<Func<News, bool>> predicate)
		{
			return CurrentObjectSet.Count(predicate);
		}

		public News GetByID(int id)
		{
			return CurrentObjectSet.First(n => n.NewsID == id);
		}

		public INewsRepository Include(string path)
		{
			CurrentObjectSet.Include(path);
			return this;
		}

		#region IReadOnlyRepository<INewsRepository,News> Members


		public INewsRepository EnableLazyLoading()
		{
			SetLazyLoading(true);
			return this;
		}

		public INewsRepository DisableLazyLoading()
		{
			SetLazyLoading(false);
			return this;
		}

		#endregion
	}
}